package cn.wolfcode.exception;

import cn.wolfcode.query.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对控制器进行增强处理
 */
@ControllerAdvice
public class HandlerControllerException {
    /**
     * 捕获项目在运行过程中出现的运行异常
     * @param e
     * @param response
     * @param method
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public Object handleException(RuntimeException e, HttpServletResponse response, HandlerMethod method){
        e.printStackTrace();//显示异常信息，方便处理bug
        String msg="操作失败，请联系管理员";
        //判断当前执行的方法是否是ajax方法
        if(method.hasMethodAnnotation(ResponseBody.class)){
            if(e instanceof LogicException){
                msg=e.getMessage();
            }
            try{
            //若是ajax方法，返回jsonResult
            JsonResult json = new JsonResult(msg, false);
            response.setContentType("application/json;charset=utf-8");

                response.getWriter().print(JSON.toJSONString(json));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }
        //若不是ajax方法，返回错误页面
        return "common/error";
    }
}
